package com.dchat.controller;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.dchat.domain.ResponseDto;
import com.dchat.domain.User;
import com.dchat.domain.UserInfo;
import com.dchat.service.inter.UserService;
import com.dchat.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Objects;

@RestController
@RequestMapping("/dchat")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private RedisOperator redisOperator;
    /**
     * 用户注册
     */
    @PostMapping("/register")
    public String register(@RequestBody String data){

        JSONObject form = JSONUtil.parseObj(data);
        String loginId = form.getStr("loginId");
        String nickname = form.getStr("nickname");
        String password = form.getStr("password");
        if (null==loginId||loginId.length()<2){
            return JSONUtil.toJsonStr(new ResponseDto<String>(false,503,"账号太短了"));
        }
        if (null==nickname){
            return JSONUtil.toJsonStr(new ResponseDto<String>(false,504,"昵称太短了"));
        }
        if (null==password||password.length()<3) {
            return JSONUtil.toJsonStr(new ResponseDto<String>(false, 505, "密码不能少于3位"));
        }
        User user = userService.getUserByLoginId(loginId);
        if(null!=user){
            return JSONUtil.toJsonStr(new ResponseDto<String>(false,506,"该账号已经被注册了"));
        }
        //默认头像
        String avatar = "http://120.76.229.17/dchat/avatar/default.png";
        User newUser = new User(null,loginId,nickname,avatar,"","", MyDateUtil.simpleDateFormat.format(new Date()),MD5.toMD5(password));


        userService.insertOne(newUser);


        return JSONUtil.toJsonStr(new ResponseDto<String>(true,200,"注册成功！"));
    }

    /**
     * 获取用户信息
     */
    @PostMapping("/getUserInfo")
    public String getUserInfo(@RequestBody String data){
        JSONObject jsonObject = JSONUtil.parseObj(data);
        //验证token是否存在或者失效
        Integer id = redisOperator.verifyToken(jsonObject.getStr("token"));
        if(id==null){
            return JSONUtil.toJsonStr(new ResponseDto<String>(false,404,"token失效或者未找到"));
        }
        User user = userService.getUserById(id);
        UserInfo userInfo = new UserInfo(user);
        return JSONUtil.toJsonStr(new ResponseDto<>(userInfo));
    }

    /**
     * 登录请求，设置token
     */
    @PostMapping("/loginPost")
    public String loginPost(@RequestBody String data){
        JSONObject jsonObject = JSONUtil.parseObj(data);

        String loginId = jsonObject.getStr("loginId").trim();
        String password = jsonObject.getStr("password").trim();

        User user = userService.getUserByLoginId(loginId);
        //返回
        ResponseDto<JSONObject> responseDto = new ResponseDto<>();
        if(user==null){
            responseDto.setSuccess(false);
            responseDto.setMessage("未注册！");
            responseDto.setCode(202);//用户不存在
            return JSONUtil.toJsonStr(responseDto);
        }else if(!Objects.equals(user.getPassword(), MD5.toMD5(password))){
            responseDto.setSuccess(false);
            responseDto.setMessage("密码错误！");
            responseDto.setCode(203);//不密码正确
            return JSONUtil.toJsonStr(responseDto);
        }else{
            //成功登录，返回token
            String token = null;
            try {

                 //todo 登录时间+登录账号作为token加密

                token = AesEncryptUtils.encrypt(new Date() +loginId);
                //缓存token
                redisOperator.setToken(token,user.getId());
            } catch (Exception e) {
                e.printStackTrace();
            }
            responseDto.setContent(new JSONObject().put("token",token));
        }
        return JSONUtil.toJsonStr(responseDto);
    }

    /**
     * 更新用户文字信息
     */
    @PostMapping("/updateUserInfo")
    public String updateUserInfo(@RequestBody String data){

        JSONObject jsonObject = JSONUtil.parseObj(data);
        //*****************验证token是否存在或者失效****************************
        Integer id = redisOperator.verifyToken(jsonObject.getStr("token"));
        if(id==null){
            return JSONUtil.toJsonStr(new ResponseDto<String>(false,404,"token失效或者未找到"));
        }
        //*****************验证结束****************************
        User user = new User();
        user.setId(id);
        jsonObject.remove("token");
        for (String item:jsonObject.keySet()){
            switch (item){
                case "nickname":
                    user.setNickname(jsonObject.getStr("nickname")); break;
                case "gender":
                    user.setGender(jsonObject.getStr("gender"));     break;
                case "signature":
                    user.setSignature(jsonObject.getStr("signature")); break;
                case "avatar":
                    user.setAvatar(jsonObject.getStr("avatar"));break;
            }
        }
        userService.updateUserById(user);
        return JSONUtil.toJsonStr(new ResponseDto<>("1"));
    }

}
